package org.itboys.core.service.mysql.front;

import org.apache.commons.lang.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.common.UserTypeEnum;
import org.itboys.core.common.WalletRecordEnum;
import org.itboys.core.dao.wallet.SundayWalletMapper;
import org.itboys.core.dao.wallet.SundayWalletRecordMapper;
import org.itboys.core.dto.wallet.SundayWalletDTO;
import org.itboys.core.dto.wallet.SundayWalletRecordDTO;
import org.itboys.core.entity.mongo.SundayMember;
import org.itboys.core.entity.mysql.wallet.SundayWallet;
import org.itboys.core.entity.mysql.wallet.SundayWalletExample;
import org.itboys.core.entity.mysql.wallet.record.SundayWalletRecord;
import org.itboys.core.entity.mysql.wallet.record.SundayWalletRecordExample;
import org.itboys.core.service.mongo.web.SundayMemberService;
import org.itboys.core.util.MybatisParamUtil;
import org.itboys.mysql.service.BaseMySqlService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author：贾琦磊
 * @Date：2018/11/27
 * @Description：钱包
 */
@Service
public class SundayFrontWalletService extends BaseMySqlService<SundayWallet> {
    @Autowired
    private SundayMemberService memberService;
    @Autowired
    private SundayWalletMapper walletMapper;
    @Autowired
    private SundayWalletRecordMapper walletRecordMapper;

    /**
     * 创建提现记录，扣除钱包金额
     *
     * @param memberId 用户id
     * @param money    金额
     * @param account  账户
     */
    public void createTXRecord(Long memberId, BigDecimal money, String account) {
        SundayWallet wallet = getWallet(memberId);
        //生成一条记录立即生效
        SundayWalletRecord record = new SundayWalletRecord(memberId,wallet.getId(),money,SundayCommonConstants.WALLET_RECORD_OPERATION_SUBTRACT
        ,WalletRecordEnum.TIXIAN.getCode(),account,SundayCommonConstants.TX_APPLY_STATE_DONE);
        walletRecordMapper.insert(record);
        //将金额减掉，已提现增加
        wallet.setMoney(wallet.getMoney().subtract(money));
        wallet.setExtract(wallet.getExtract().add(money));
        walletMapper.update(wallet);
    }

    /**
     * 充值
     *
     * @param memberId
     * @param amount
     * @return
     */
    public Map<String, Object> createCZRecord(Long memberId, BigDecimal amount) {
        //准备返回结果
        Map<String, Object> result = new HashMap<String, Object>();
        SundayWallet wallet = getWallet(memberId);
        //创建一个钱包记录，用户id:memberId,钱包id:walletId，
        // 金额:amount,运算方式:+，记录类型:充值,
        SundayWalletRecord record = new SundayWalletRecord(
                memberId, wallet.getId(), amount, SundayCommonConstants.WALLET_RECORD_OPERATION_ADD,
                WalletRecordEnum.CHONGZHI.getCode(), "用户充值", 0);
        walletRecordMapper.insert(record);
        result.put("payAmount", record.getMoney().setScale(2, BigDecimal.ROUND_HALF_UP));//本次付款金额
        result.put("recordId", record.getId());
        // result.put("type", 1);//余额充值
        return result;
    }

    public SundayWallet getWallet(Long memberId) {
        SundayWalletExample example = new SundayWalletExample();
        example.createCriteria().andIsDeletedEqualTo(SundayCommonConstants.NO).andMemberIdEqualTo(memberId);
        SundayWallet wallet = null;
        List<SundayWallet> wallets = walletMapper.selectByExample(example);
        if (ListUtil.isNotNull(wallets)) {
            wallet = wallets.get(0);
        } else {
            wallet = new SundayWallet();
            wallet.setMemberId(memberId);
            wallet.setMoney(BigDecimal.ZERO);
            wallet.setExtract(BigDecimal.ZERO);
            wallet.setSum(BigDecimal.ZERO);
            walletMapper.insert(wallet);
        }
        return wallet;
    }

    /**
     * 获取账户余额，供应商获取余额和记录
     *
     * @param memberId
     * @return
     */
    public Object getBalance(Long memberId, String ct) throws ParseException {
        SundayMember member = memberService.getById(memberId);
        if (member == null){ throw new ErrorException(ExceptionEnum.USER_NONENTITY.getValue());};
        Integer type = member.getUserType();
        SundayWallet wallet = getWallet(memberId);
        BigDecimal money = wallet.getMoney();
        if (type.equals(UserTypeEnum.LEASE.getCode()) || type.equals(UserTypeEnum.COMPANY.getCode())) {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("money", money);
            return result;
        } else if (type.equals(UserTypeEnum.SUPPLIER.getCode())) {
            SundayWalletDTO result = new SundayWalletDTO();
            BeanUtils.copyProperties(wallet, result);
            SundayWalletRecordExample recordExample = new SundayWalletRecordExample();
            recordExample.setSortOrder("desc");
            recordExample.setOrderByClause("ct");
            SundayWalletRecordExample.Criteria criteria = recordExample.createCriteria()
                    .andIsDeletedEqualTo(SundayCommonConstants.NO)
                    .andWalletIdEqualTo(wallet.getId())
                    .andStatusNotEqualTo(SundayCommonConstants.NO);
            if (StringUtils.isNotEmpty(ct)){criteria.andCtEqualTo(ct);}
            List<SundayWalletRecord> records = walletRecordMapper.selectByExample(recordExample);
            //获取当前月份
            Calendar calendar = Calendar.getInstance();
            int month = calendar.get(Calendar.MONTH) + 1;
            BigDecimal mouthIncome = BigDecimal.ZERO;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (SundayWalletRecord record : records
                    ) {
                String createDate = record.getCreateDate();
                Date date = sdf.parse(createDate);
                calendar.setTime(date);
                int createMouth = calendar.get(Calendar.MONTH) + 1;
                if (createMouth == month && SundayCommonConstants.WALLET_RECORD_OPERATION_ADD.equals(record.getOperation())) {
                    mouthIncome = mouthIncome.add(record.getMoney());
                }
            }
            result.setMonthIncome(mouthIncome);
            List<SundayWalletRecordDTO> dtos = new ArrayList<>();
            if (ListUtil.isNotNull(records)) {
                for (SundayWalletRecord r : records
                        ) {

                    SundayWalletRecordDTO dto = new SundayWalletRecordDTO();
                    BeanUtils.copyProperties(r, dto);
                    dto.setRemark(WalletRecordEnum.getDesc(r.getType()));
                    //dto.setState(r.getStatus()==1?"已生效":"未生效");
                    String operationStr = r.getOperation() > 0 ? "+" : "-";
                    dto.setMoney(operationStr + r.getMoney());
                    dtos.add(dto);
                }
            }
            result.setRecordDTOS(dtos);
            return result;
        }
        throw new ErrorException(ExceptionEnum.USER_TYPE_ERROR.getValue());
    }

    /**
     * 租赁端分页查询钱包记录
     *
     * @param ct
     * @param memberId
     * @param paramUtil
     * @return
     */
    public List<SundayWalletRecordDTO> record(String ct, Long memberId, MybatisParamUtil paramUtil) {
        SundayWalletRecordExample example = new SundayWalletRecordExample();
        //分页参数
        example.setOrderByClause(paramUtil.getSortName());
        example.setSortOrder(paramUtil.getSortOrder());
        example.setPageSize(paramUtil.getRowSize());
        example.setStartRow(paramUtil.getRowStart());
        //where条件
        SundayWalletRecordExample.Criteria criteria = example.createCriteria()
                .andIsDeletedEqualTo(SundayCommonConstants.NO)
                .andMemberIdEqualTo(memberId)
                .andStatusEqualTo(SundayCommonConstants.YES);
        if (StringUtils.isNotEmpty(ct)) criteria.andCtEqualTo(ct);
        List<SundayWalletRecord> data = walletRecordMapper.selectByExample(example);
        List<SundayWalletRecordDTO> result = new ArrayList<>();
        if (!ListUtil.isNotNull(data)) {
            return result;
        }
        for (SundayWalletRecord r : data
                ) {
            SundayWalletRecordDTO dto = new SundayWalletRecordDTO();
            BeanUtils.copyProperties(r, dto);
            dto.setRemark(WalletRecordEnum.getDesc(r.getType()));
            //dto.setState(r.getStatus()==1?"已生效":"未生效");
            String operationStr = r.getOperation() > 0 ? "+" : "-";
            dto.setMoney(operationStr + r.getMoney());
            result.add(dto);
        }
        return result;
    }

    /**
     * 支付回调
     */
    @Transactional
    public void chargeBack(SundayWalletRecord record) {
        SundayWallet wallet = getWallet(record.getMemberId());
        record.setStatus(SundayCommonConstants.YES);
        BigDecimal addScore = record.getMoney();
        record.setMoney(addScore);
        walletRecordMapper.update(record);
        if (SundayCommonConstants.WALLET_RECORD_OPERATION_ADD.equals(record.getOperation())) {
            wallet.setMoney(wallet.getMoney().add(record.getMoney()));
        } else if (SundayCommonConstants.WALLET_RECORD_OPERATION_SUBTRACT.equals(record.getOperation())) {
            wallet.setMoney(wallet.getMoney().subtract(record.getMoney()));
        }
        walletMapper.update(wallet);
    }
}
